import React, {
  ReactElement,
  useContext,
  useEffect,
  useMemo,
  useState
} from 'react';
import { View, Text, DeviceEventEmitter } from 'react-native';

import styles from './style';
import { Store } from '../../../../reducer';
import { computeTime } from '../../../../func';
import { CurrentTimeChangeData } from '../../../../types';
import { CLASS_ROOM_EVENT_CURRENT_TIME_CHANGE } from '../../../../event';

export default (): ReactElement => {
  const [showTime, setShowTime] = useState('00:00:00');

  const { state } = useContext(Store);
  const { classRoomChangeTime } = state;

  useEffect((): (() => void) => {
    const subscription = DeviceEventEmitter.addListener(
      CLASS_ROOM_EVENT_CURRENT_TIME_CHANGE,
      (data: CurrentTimeChangeData): void => {
        const { time } = data;
        const currentTime =
          classRoomChangeTime > -1 ? classRoomChangeTime : time;
        setShowTime(computeTime(currentTime / 1000));
      }
    );
    return (): void => {
      if (subscription) {
        subscription.remove();
      }
    };
  }, [classRoomChangeTime]);

  return useMemo(
    (): ReactElement => (
      <View style={styles.currentContent}>
        <Text style={styles.time}>{showTime}</Text>
      </View>
    ),
    [showTime]
  );
};
